<%doc>
USAGE DOCUMENTATION :: PLEASE LEAVE THIS AT THE TOP OF THIS FILE

For Mako templating syntax documentation please visit: http://docs.makotemplates.org/en/latest/

Filename:           mobile_devices_table.html
Version:            0.1

DOCUMENTATION :: END
</%doc>

<ul class="stacked-configs list-unstyled">
    % for device in sorted(devices_list, key=lambda k: ((k['friendly_name'] or k['device_name']).lower(), k['id'])):
    <li class="mobile-device pointer" data-id="${device['id']}" data-name="${device['device_name']}">
        <span>
            % if device['official'] == -1:
                <span class="toggle-left official-tooltip" data-toggle="tooltip" data-placement="top" title="OneSignal Validation Failed"><i class="fa fa-lg fa-fw fa-exclamation-triangle"></i></span>
            % elif device['official'] > 0:
                <%
                    icon = 'mobile'
                    if device['platform'] == 'android':
                        icon = 'android'
                    elif device['platform'] == 'ios':
                        icon = 'apple'
                %>
                <span class="toggle-left"><i class="fa fa-lg fa-fw fa-${icon}"></i></span>
            % else:
                <span class="toggle-left official-tooltip" data-toggle="tooltip" data-placement="top" title="Unofficial or Unknown App"><i class="fa fa-lg fa-fw fa-exclamation-triangle"></i></span>
            % endif
            ${device['friendly_name'] or device['device_name']} &nbsp;<span class="friendly_name">(${device['id']})</span>
            <span class="toggle-right friendly_name">
                % if device['last_seen']:
                <span id="device-last_seen-${device['id']}">
                    <script>
                        $("#device-last_seen-${device['id']}").text(moment("${device['last_seen']}", "X").fromNow())
                    </script>
                </span>
                % else:
                never
                % endif
                <i class="fa fa-lg fa-fw fa-cog"></i></span>
            </span>
        </span>
    </li>
    % endfor
    <li class="add-mobile-device pointer" id="register-mobile-device" data-target="#api-qr-modal" data-toggle="modal">
        <span>
            <span class="toggle-left"><i class="fa fa-lg fa-fw fa-mobile"></i></span> Register a new device
            <span class="toggle-right"><i class="fa fa-lg fa-fw fa-plus"></i></span>
        </span>
    </li>
</ul>

<script>
    // Load notification agent config modal
    $(".mobile-device").click(function () {
        var mobile_device_id = $(this).data('id');
        loadMobileDeviceConfig(mobile_device_id);
    });

    getPlexPyURL = function () {
        var deferred = $.Deferred();
        if (location.hostname !== "localhost" && location.hostname !== "127.0.0.1" && location.hostname !== "[::1]") {
            deferred.resolve(location.href.split('/settings')[0]);
        } else {
            $.get('get_plexpy_url').then(function (url) {
                deferred.resolve(url);
            })
        }
        return deferred;
    };

    function checkQRAddress(url) {
        var parser = document.createElement('a');
        parser.setAttribute('href', url);
        var hostname = parser.hostname;
        var protocol = parser.protocol;

        if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]') {
            $('#api_qr_localhost').toggle(true);
            $('#api_qr_private').toggle(false);
        } else {
            $('#api_qr_localhost').toggle(false);
            isPrivateIP(hostname).then(function (valid) {
                $('#api_qr_private').toggle((valid !== 'n/a'));
            }, function () {
                $('#api_qr_private').toggle(false);
            });
        }
        $('#api_qr_https').toggle((protocol === 'http:'));
    }

    function generateQRCode(url) {
        $('#api_qr_code').empty().kjua({
            text: url + '|' + $('#api_qr_token').val(),
            render: 'canvas',
            ecLevel: 'H',
            size: 256,
            fill: '#000',
            back: '#eee'
        });
    }

    var verifiedDevice = false;
    $('#register-mobile-device').click(function () {
        verifiedDevice = false;

        getPlexPyURL().then(function (url) {
            checkQRAddress(url);

            $.get('generate_api_key', { device: true }).then(function (token) {
                $('#api_qr_address').val(url);
                $('#api_qr_token').val(token);
                generateQRCode(url);

                (function poll() {
                    setTimeout(function () {
                        $.ajax({
                            url: 'verify_mobile_device',
                            type: 'GET',
                            data: {
                                device_token: token
                            },
                            success: function (data) {
                                if (data.result === 'success') {
                                    verifiedDevice = true;
                                    getMobileDevicesTable();
                                    $('#api-qr-modal').modal('hide');
                                    showMsg('<i class="fa fa-check"></i> ' + data.message, false, true, 5000, false);
                                }
                            },
                            complete: function () {
                                if (!(verifiedDevice)) {
                                    poll();
                                }
                            },
                            timeout: 1000
                        });
                    }, 1000);
                })();
            });
        });
    });

    $('#api_qr_address').change(function () {
        this.value = $.trim(this.value);
        var url = $(this).val();
        checkQRAddress(url);
        generateQRCode(url);
    });

    $('#api-qr-modal').on('hide.bs.modal', function () {
        if (!(verifiedDevice)) {
            $.ajax({
                url: 'verify_mobile_device',
                type: 'GET',
                data: {
                    device_token: $('#api_qr_token').val(),
                    cancel: true
                },
                success: function (data) {
                    showMsg('<i class="fa fa-times"></i> ' + data.message, false, true, 5000, false);
                }
            });
        }
        verifiedDevice = true;
    })

    $('.official-tooltip').tooltip();
</script>